package com.fary.chapter02_safe_thread;

import lombok.SneakyThrows;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock的使用方式
 */
public class SafeThread08 extends Thread{
    private int count = 100;
    private Lock lock = new ReentrantLock();

    @SneakyThrows
    @Override
    public void run() {
        while (true) {
            Thread.sleep(30);
            try {
                // 获取锁
                lock.lock();
                if (count > 1) {
                    count--;
                    System.out.println(Thread.currentThread().getName() + "," + count);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 释放锁
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        SafeThread08 safeThread08 = new SafeThread08();
        Thread t1 = new Thread(safeThread08);
        Thread t2 = new Thread(safeThread08);
        t1.start();
        t2.start();
    }
}
